<?php
/**
 * 结算管理
 *
 *
 *
 *
 * @好商城提供技术支持 授权请购买shopnc授权
 * @license    http://www.33hao.com
 * @link       交流群号：138182377
 */


defined('In33hao') or exit('Access Invalid!');

class agent_billControl extends SystemControl
{
    /**
     * 每次导出订单数量
     * @var int
     */
    const EXPORT_SIZE = 1000;

    private $links = array(
        array('url' => 'act=bill&op=index', 'lang' => 'nc_manage'),
    );

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 结算单列表
     *
     */
    public function indexOp()
    {
        Tpl::setDirquna('shop');
        Tpl::showpage('ag_bill.index');
    }

    /**
     * 某店铺某月订单列表
     *
     */
    public function show_billOp()
    {
        $ob_id = intval($_GET['ob_id']);
        if ($ob_id <= 0) {
            showMessage('参数错误', '', 'html', 'error');
        }
        $model_bill = Model('fenxiao_bill');
        $bill_info = $model_bill->getSqOrderBillInfo(array('ob_id' => $ob_id));
        if (!$bill_info) {
            showMessage('参数错误', '', 'html', 'error');
        }
        $sub_tpl_name = 'sq_bill.show.code_list';
        Tpl::output('tpl_name', $sub_tpl_name);
        Tpl::output('bill_info', $bill_info);

        Tpl::setDirquna('shop');
        Tpl::showpage('ag_bill.show');
    }

    public function get_bill_info_code_xmlOp()
    {
        $ob_id = intval($_GET['ob_id']);
        if ($ob_id <= 0) {
            exit();
        }
        $model_bill = Model('fenxiao_bill');
        $bill_info = $model_bill->getSqOrderBillInfo(array('ob_id' => $ob_id));
        if (!$bill_info) {
            exit();
        }
        $model_order = Model('vr_order');
        $condition = array();
        if ($_POST['query'] != '' && in_array($_POST['qtype'], array('vr_code', 'buyer_name'))) {
            if ($_POST['qtype'] == 'vr_code') {
                $condition['vr_code'] = array('like', "%{$_POST['query']}%");
            } else {
                $order_list = $model_order->getOrderList(array('buyer_name' => array('like', "%{$_POST['query']}%")), '', 'order_id');
                if (!empty($order_list)) {
                    $order_id_list = array();
                    foreach ($order_list as $order_info) {
                        $order_id_list[] = $order_info['order_id'];
                    }
                    $condition['order_id'] = array('in', $order_id_list);
                } else {
                    $condition['order_id'] = 0;
                }
            }
        }
        $sort_fields = array('vr_indate', 'vr_usetime', 'buyer_id');
        if (in_array($_POST['sortorder'], array('asc', 'desc')) && in_array($_POST['sortname'], $sort_fields)) {
            $order = $_POST['sortname'] . ' ' . $_POST['sortorder'];
        }
        $condition['store_id'] = $bill_info['ob_store_id'];
        if ($_GET['query_type'] == 'timeout') {
            //计算未使用已过期不可退兑换码列表
            $condition['vr_state'] = 0;
            $condition['vr_invalid_refund'] = 0;
            $condition['vr_indate'] = array('between', "{$bill_info['ob_start_date']},{$bill_info['ob_end_date']}");
        } else {
            //计算已使用兑换码列表
            $condition['vr_state'] = 1;
            $condition['vr_usetime'] = array('between', "{$bill_info['ob_start_date']},{$bill_info['ob_end_date']}");
        }
        $code_list = $model_order->getCodeList($condition, '*', $_POST['rp'], $order);
//        dd($model_order->db->sql);
        //然后取订单编号
        $order_id_array = array();
        if (is_array($code_list)) {
            foreach ($code_list as $code_info) {
                $order_id_array[] = $code_info['order_id'];
            }
        }
        $condition = array();
        $condition['order_id'] = array('in', $order_id_array);
        $order_list = $model_order->getOrderList($condition);
        $order_new_list = array();
        if (!empty($order_list)) {
            foreach ($order_list as $v) {
                $order_new_list[$v['order_id']]['order_sn'] = $v['order_sn'];
                $order_new_list[$v['order_id']]['buyer_name'] = $v['buyer_name'];
                $order_new_list[$v['order_id']]['store_name'] = $v['store_name'];
                $order_new_list[$v['order_id']]['store_id'] = $v['store_id'];
            }
        }

        $data = array();
        $data['now_page'] = $model_order->shownowpage();
        $data['total_num'] = $model_order->gettotalnum();
        foreach ($code_list as $code_info) {
            $list = array();
            $list['operation'] = "<a class=\"btn green\" href=\"index.php?act=vr_order&op=show_order&order_id={$code_info['order_id']}\"><i class=\"fa fa-list-alt\"></i>查看</a>";
            $list['vr_code'] = $code_info['vr_code'];
            $list['ob_start_date'] = $_GET['query_type'] == 'timeout' ? date('Y-m-d', $code_info['vr_indate']) : date('Y-m-d H:i:s', $code_info['vr_usetime']);
            $list['order_sn'] = $order_new_list[$code_info['order_id']]['order_sn'];
            $list['pay_price'] = ncPriceFormat($code_info['pay_price']);
            $list['commis_rate'] = ncPriceFormat($code_info['pay_price'] * $code_info['commis_rate'] / 100);
            $list['buyer_name'] = $order_new_list[$code_info['order_id']]['buyer_name'];
            $list['buyer_id'] = $code_info['buyer_id'];
            $data['list'][$code_info['rec_id']] = $list;
        }
        exit(Tpl::flexigridXML($data));
    }


    public function get_bill_info_xmlOp()
    {
        $ob_id = intval($_GET['ob_id']);
        if ($ob_id <= 0) {
            exit();
        }
        $model_bill = Model('bill');
        $bill_info = $model_bill->getOrderBillInfo(array('ob_id' => $ob_id));
        if (!$bill_info) {
            exit();
        }

        $order_condition = array();
        $order_condition['order_state'] = ORDER_STATE_SUCCESS;
        $order_condition['store_id'] = $bill_info['ob_store_id'];
        $if_start_date = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $_GET['query_start_date']);
        $if_end_date = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $_GET['query_end_date']);
        $start_unixtime = $if_start_date ? strtotime($_GET['query_start_date']) : null;
        $end_unixtime = $if_end_date ? strtotime($_GET['query_end_date']) : null;
        $end_unixtime = $if_end_date ? $end_unixtime + 86400 - 1 : null;
        if ($if_start_date || $if_end_date) {
            $order_condition['finnshed_time'] = array('between', "{$start_unixtime},{$end_unixtime}");
        } else {
            $order_condition['finnshed_time'] = array('between', "{$bill_info['ob_start_date']},{$bill_info['ob_end_date']}");
        }
        if ($_GET['query_type'] == 'refund') {
            //退款订单列表
            $model_refund = Model('refund_return');
            $refund_condition = array();
            $refund_condition['seller_state'] = 2;
            $refund_condition['store_id'] = $bill_info['ob_store_id'];
            $refund_condition['goods_id'] = array('gt', 0);
            $refund_condition['admin_time'] = $order_condition['finnshed_time'];
            if ($_POST['query'] != '' && in_array($_POST['qtype'], array('refund_sn', 'order_sn', 'buyer_name'))) {
                $refund_condition[$_POST['qtype']] = array('like', "%{$_POST['query']}%");
            }
            $sort_fields = array('refund_amount', 'commis_amount', 'refund_type', 'admin_time', 'buyer_id', 'store_id');
            if (in_array($_POST['sortorder'], array('asc', 'desc')) && in_array($_POST['sortname'], $sort_fields)) {
                $order = $_POST['sortname'] . ' ' . $_POST['sortorder'];
            }
            $refund_list = $model_refund->getRefundReturnList($refund_condition, $_POST['rp'], 'refund_return.*,ROUND(refund_amount*commis_rate/100,2) as commis_amount', '', $order);
            if (is_array($refund_list) && count($refund_list) == 1 && $refund_list[0]['refund_id'] == '') {
                $refund_list = array();
            }
            $data = array();
            $data['now_page'] = $model_refund->shownowpage();
            $data['total_num'] = $model_refund->gettotalnum();
            foreach ($refund_list as $refund_info) {
                $list = array();
                if ($refund_info['refund_type'] == 1) {
                    $list['operation'] = "<a class=\"btn green\" href=\"index.php?act=refund&op=view&refund_id={$refund_info['refund_id']}\"><i class=\"fa fa-list-alt\"></i>查看</a>";
                } else {
                    $list['operation'] = "<a class=\"btn green\" href=\"index.php?act=return&op=view&return_id={$refund_info['refund_id']}\"><i class=\"fa fa-list-alt\"></i>查看</a>";
                }
                $list['refund_sn'] = $refund_info['refund_sn'];
                $list['order_sn'] = $refund_info['order_sn'];
                $list['refund_amount'] = ncPriceFormat($refund_info['refund_amount']);
                $list['commis_amount'] = ncPriceFormat($refund_info['commis_amount']);
                $list['rpt_amount'] = ncPriceFormat($refund_info['rpt_amount']);
                $list['refund_type'] = str_replace(array(1, 2), array('退款 ', '退货'), $refund_info['refund_type']);
                $list['admin_time'] = date('Y-m-d', $refund_info['admin_time']);
                $list['buyer_name'] = $refund_info['buyer_name'];
                $list['buyer_id'] = $refund_info['buyer_id'];
                $list['store_name'] = $refund_info['store_name'];
                $list['store_id'] = $refund_info['store_id'];
                $data['list'][$refund_info['refund_id']] = $list;
            }
            exit(Tpl::flexigridXML($data));
        } elseif ($_GET['query_type'] == 'cost') {

            //店铺费用
            $model_store_cost = Model('store_cost');
            $cost_condition = array();
            $cost_condition['cost_store_id'] = $bill_info['ob_store_id'];
            $cost_condition['cost_time'] = $order_condition['finnshed_time'];
            $store_cost_list = $model_store_cost->getStoreCostList($cost_condition, $_POST['rp'], 'cost_id desc');
            //取得店铺名字
            $store_info = Model('store')->getStoreInfoByID($bill_info['ob_store_id']);
            $data = array();
            $data['now_page'] = $model_store_cost->shownowpage();
            $data['total_num'] = $model_store_cost->gettotalnum();
            foreach ($store_cost_list as $store_cost_info) {
                $list = array();
                $list['store_name'] = $store_info['store_name'];
                $list['cost_remark'] = $store_cost_info['cost_remark'];
                $list['cost_price'] = ncPriceFormat($store_cost_info['cost_price']);
                $list['cost_time'] = date('Y-m-d', $store_cost_info['cost_time']);
                $data['list'][$store_cost_info['cost_id']] = $list;
            }
            exit(Tpl::flexigridXML($data));
        } elseif ($_GET['query_type'] == 'book') {

            $condition = array();
            //被取消的预定订单列表
            $model_order = Model('order');
            if ($_POST['query'] != '' && in_array($_POST['qtype'], array('order_sn'))) {
                $order_info = $model_order->getOrderInfo(array('order_sn' => $_POST['query']));
                if ($order_info) {
                    $condition['book_order_id'] = $order_info['order_id'];
                } else {
                    $condition['book_order_id'] = 0;
                }
            }

            $model_order_book = Model('order_book');

            $condition['book_store_id'] = $bill_info['ob_store_id'];
            $condition['book_cancel_time'] = $order_condition['finnshed_time'];
            unset($order_condition['finnshed_time']);
            $order_book_list = $model_order_book->getOrderBookList($condition, $_POST['rp'], 'book_id desc', '*');

            //然后取订单信息
            $tmp_book = array();
            $order_id_array = array();
            if (is_array($order_book_list)) {
                foreach ($order_book_list as $order_book_info) {
                    $order_id_array[] = $order_book_info['book_order_id'];
                    $tmp_book[$order_book_info['book_order_id']]['book_cancel_time'] = $order_book_info['book_cancel_time'];
                    $tmp_book[$order_book_info['book_order_id']]['book_real_pay'] = $order_book_info['book_real_pay'];
                }
            }
            $order_list = $model_order->getOrderList(array('order_id' => array('in', $order_id_array)));
            $data = array();
            $data['now_page'] = $model_order->shownowpage();
            $data['total_num'] = $model_order->gettotalnum();
            foreach ($order_list as $order_info) {
                $list = array();
                $list['operation'] = "<a class=\"btn green\" href=\"index.php?act=order&op=show_order&order_id={$order_info['order_id']}\"><i class=\"fa fa-list-alt\"></i>查看</a>";
                $list['order_sn'] = $order_info['order_sn'];
                $list['order_amount'] = ncPriceFormat($order_info['order_amount']);
                $list['shipping_fee'] = ncPriceFormat($order_info['shipping_fee']);
                $list['deposit_amount'] = ncPriceFormat($tmp_book[$order_info['order_id']]['book_real_pay']);
                $list['add_time'] = date('Y-m-d', $order_info['add_time']);
                $list['cancel_time'] = date('Y-m-d', $tmp_book[$order_info['order_id']]['book_cancel_time']);
                $list['buyer_name'] = $order_info['buyer_name'];
                $list['buyer_id'] = $order_info['buyer_id'];
                $list['store_name'] = $order_info['store_name'];
                $list['store_id'] = $order_info['store_id'];
                $data['list'][$order_info['order_id']] = $list;
            }
            exit(Tpl::flexigridXML($data));
        } else {

            //订单列表
            $model_order = Model('order');
            if ($_POST['query'] != '' && in_array($_POST['qtype'], array('order_sn', 'buyer_name'))) {
                $order_condition[$_POST['qtype']] = array('like', "%{$_POST['query']}%");
            }
            if ($_GET['order_sn'] != '') {
                $order_condition['order_sn'] = array('like', "%{$_GET['order_sn']}%");
            }
            if ($_GET['buyer_name'] != '') {
                if ($_GET['jq_query']) {
                    $order_condition['buyer_name'] = $_GET['buyer_name'];
                } else {
                    $order_condition['buyer_name'] = array('like', "%{$_GET['buyer_name']}%");
                }
            }

            $sort_fields = array('order_amount', 'shipping_fee', 'commis_amount', 'add_time', 'finnshed_time', 'buyer_id', 'store_id');
            if (in_array($_POST['sortorder'], array('asc', 'desc')) && in_array($_POST['sortname'], $sort_fields)) {
                $order = $_POST['sortname'] . ' ' . $_POST['sortorder'];
            }
            $order_list = $model_order->getOrderList($order_condition, $_POST['rp'], '*', $order);

            //然后取订单商品佣金
            $order_id_array = array();
            if (is_array($order_list)) {
                foreach ($order_list as $order_info) {
                    $order_id_array[] = $order_info['order_id'];
                }
            }
            $order_goods_condition = array();
            $order_goods_condition['order_id'] = array('in', $order_id_array);
            $field = 'SUM(ROUND(goods_pay_price*commis_rate/100,2)) as commis_amount,order_id';
            $commis_list = $model_order->getOrderGoodsList($order_goods_condition, $field, null, null, '', 'order_id', 'order_id');

            $data = array();
            $data['now_page'] = $model_order->shownowpage();
            $data['total_num'] = $model_order->gettotalnum();
            foreach ($order_list as $order_info) {
                $list = array();
                $list['operation'] = "<a class=\"btn green\" href=\"index.php?act=order&op=show_order&order_id={$order_info['order_id']}\"><i class=\"fa fa-list-alt\"></i>查看</a>";
                $list['order_sn'] = $order_info['order_sn'];
                $list['order_amount'] = ncPriceFormat($order_info['order_amount']);
                $list['shipping_fee'] = ncPriceFormat($order_info['shipping_fee']);
                $list['commis_amount'] = ncPriceFormat($commis_list[$order_info['order_id']]['commis_amount']);
                $list['rpt_amount'] = ncPriceFormat($order_info['rpt_amount']);
                $list['add_time'] = date('Y-m-d', $order_info['add_time']);
                $list['finnshed_time'] = date('Y-m-d', $order_info['finnshed_time']);
                $list['buyer_name'] = $order_info['buyer_name'];
                $list['buyer_id'] = $order_info['buyer_id'];
                $list['store_name'] = $order_info['store_name'];
                $list['store_id'] = $order_info['store_id'];
                $data['list'][$order_info['order_id']] = $list;
            }
            exit(Tpl::flexigridXML($data));
        }
    }


    /**
     * 打印结算单
     *
     */
    public function bill_printOp()
    {
        $ob_id = intval($_GET['ob_id']);
        if ($ob_id <= 0) {
            showMessage('参数错误', '', 'html', 'error');
        }
        $model_bill = Model('bill');
        $condition = array();
        $condition['ob_id'] = $ob_id;
        $condition['ob_state'] = BILL_STATE_SUCCESS;
        $bill_info = $model_bill->getOrderBillInfo($condition);
        if (!$bill_info) {
            showMessage('参数错误', '', 'html', 'error');
        }

        Tpl::output('bill_info', $bill_info);

        Tpl::setDirquna('shop');
        Tpl::showpage('bill.print', 'null_layout');
    }


    /**
     * 导出平台月出账单表
     *
     */
    public function export_billOp()
    {
        $model_bill = Model('fenxiao_bill');
        $condition = array();
        if (preg_match('/^[\d,]+$/', $_GET['ob_id'])) {
            $_GET['ob_id'] = explode(',', trim($_GET['ob_id'], ','));
            $condition['ob_id'] = array('in', $_GET['ob_id']);
        }
        list($condition, $order) = $this->_get_bill_condition($condition);

        if (!is_numeric($_GET['curpage'])) {
            $count = $model_bill->getAgBillList($condition);
            $array = array();
            if ($count > self::EXPORT_SIZE) {
                //显示下载链接
                $page = ceil($count / self::EXPORT_SIZE);
                for ($i = 1; $i <= $page; $i++) {
                    $limit1 = ($i - 1) * self::EXPORT_SIZE + 1;
                    $limit2 = $i * self::EXPORT_SIZE > $count ? $count : $i * self::EXPORT_SIZE;
                    $array[$i] = $limit1 . ' ~ ' . $limit2;
                }
                Tpl::output('list', $array);
                Tpl::output('murl', 'javascript:history.back(-1)');
                Tpl::showpage('export.excel');
                exit();
            }
            $limit = false;
        } else {
            //下载
            $limit1 = ($_GET['curpage'] - 1) * self::EXPORT_SIZE;
            $limit2 = self::EXPORT_SIZE;
            $limit = "{$limit1},{$limit2}";
        }
        $data = $model_bill->getAgBillList($condition, '*', '', 'ob_id desc', $limit);

        $export_data = array();
        $export_data[0] = array('账单编号', '出账日期', '商家ID', '商家名称', '开始日期', '结束日期','账单状态', '订单金额', '分销佣金', '本期应结');
        $ob_order_totals = 0;
        $ob_commis_totals = 0;
        $ob_result_totals = 0;
        foreach ($data as $k => $v) {
            $export_data[$k + 1][] = $v['ob_id'];
            $export_data[$k + 1][] = date('Y-m-d', $v['ob_create_date']);
            $export_data[$k + 1][] = $v['ob_store_id'];
            $export_data[$k + 1][] = $v['ob_store_name'];
            $export_data[$k + 1][] = date('Y-m-d', $v['ob_start_date']);
            $export_data[$k + 1][] = date('Y-m-d', $v['ob_end_date']);
            $export_data[$k + 1][] = billState($v['ob_state']);
            $ob_order_totals += $export_data[$k + 1][] = $v['ob_order_totals'];
            $ob_commis_totals += $export_data[$k + 1][] = $v['ob_commis_totals'];
            $ob_result_totals += $export_data[$k + 1][] = $v['ob_result_totals'];
        }
        $count = count($export_data);
        $export_data[$count][] = '';
        $export_data[$count][] = '';
        $export_data[$count][] = '';
        $export_data[$count][] = '';
        $export_data[$count][] = '';
        $export_data[$count][] = '';
        $export_data[$count][] = '合计';
        $export_data[$count][] = $ob_order_totals;
        $export_data[$count][] = $ob_commis_totals;
        $export_data[$count][] = $ob_result_totals;
        $csv = new Csv();
        $export_data = $csv->charset($export_data, CHARSET, 'gbk');
        $csv->filename = 'bill';
        $csv->export($export_data);
    }

    /**
     * 导出兑换码明细CSV
     *
     */
    public function export_orderOp(){
        $ob_id = intval($_GET['ob_id']);
        if ($ob_id <= 0) {
            showMessage('参数错误','','html','error');
        }
        $model_bill = Model('fenxiao_bill');
        $bill_info = $model_bill->getSqOrderBillInfo(array('ob_id'=>$ob_id));
        if (!$bill_info){
            showMessage('参数错误','','html','error');
        }
        $model_order = Model('vr_order');
        $condition = array();
        $condition['store_id'] = $bill_info['ob_store_id'];
        if ($_GET['query_type'] == 'timeout') {
            //计算未使用已过期不可退兑换码列表
            $condition['vr_state'] = 0;
            $condition['vr_invalid_refund'] = 0;
            $condition['vr_indate'] = array('between',"{$bill_info['ob_start_date']},{$bill_info['ob_end_date']}");
        } else {
            //计算已使用兑换码列表
            $condition['vr_state'] = 1;
            $condition['vr_usetime'] = array('between',"{$bill_info['ob_start_date']},{$bill_info['ob_end_date']}");
        }
        if (preg_match('/^[\d,]+$/', $_GET['rec_id'])) {
            $_GET['rec_id'] = explode(',',trim($_GET['rec_id'],','));
            $condition['rec_id'] = array('in',$_GET['rec_id']);
        }
        if (!is_numeric($_GET['curpage'])){
            $count = $model_order->getOrderCodeCount($condition);
            $array = array();
            if ($count > self::EXPORT_SIZE ){
                //显示下载链接
                $page = ceil($count/self::EXPORT_SIZE);
                for ($i=1;$i<=$page;$i++){
                    $limit1 = ($i-1)*self::EXPORT_SIZE + 1;
                    $limit2 = $i*self::EXPORT_SIZE > $count ? $count : $i*self::EXPORT_SIZE;
                    $array[$i] = $limit1.' ~ '.$limit2 ;
                }
                Tpl::output('list',$array);
                Tpl::output('murl','index.php?act=agent_bill&op=show_bill&ob_id='.$ob_id);
                Tpl::setDirquna('shop');
                Tpl::showpage('export.excel');
                exit();
            }else{
                //如果数量小，直接下载
                $data = $model_order->getCodeList($condition,'*','','rec_id desc',self::EXPORT_SIZE);
            }
        }else{
            //下载
            $limit1 = ($_GET['curpage']-1) * self::EXPORT_SIZE;
            $limit2 = self::EXPORT_SIZE;
            $data = $model_order->getCodeList($condition,'*','','rec_id desc',"{$limit1},{$limit2}");
        }

        //然后取订单编号
        $order_id_array = array();
        if (is_array($data)) {
            foreach ($data as $code_info) {
                $order_id_array[] = $code_info['order_id'];
            }
        }
        $condition = array();
        $condition['order_id'] = array('in',$order_id_array);
        $order_list = $model_order->getOrderList($condition);
        $order_new_list = array();
        if (!empty($order_list)) {
            foreach ($order_list as $v) {
                $order_new_list[$v['order_id']]['order_sn'] = $v['order_sn'];
                $order_new_list[$v['order_id']]['buyer_name'] = $v['buyer_name'];
                $order_new_list[$v['order_id']]['buyer_id'] = $v['buyer_id'];
                $order_new_list[$v['order_id']]['store_name'] = $v['store_name'];
                $order_new_list[$v['order_id']]['store_id'] = $v['store_id'];
                $order_new_list[$v['order_id']]['goods_name'] = $v['goods_name'];
            }
        }

        $export_data = array();
        $export_data[0] = array('兑换码','消费时间','订单号','消费金额','佣金金额','商家','商家编号','买家','买家编号','商品');
        if ($_GET['query_type'] == 'timeout') {
            $export_data[0][1] = '过期时间';
        }

        $pay_totals = 0;
        $commis_totals = 0;
        $k = 0;
        foreach ($data as $v) {
            //该订单算佣金
            $export_data[$k+1][] = $v['vr_code'];
            if ($_GET['query_type'] == 'timeout') {
                $export_data[$k+1][] = date('Y-m-d H:i:s',$v['vr_indate']);
            } else {
                $export_data[$k+1][] = date('Y-m-d H:i:s',$v['vr_usetime']);
            }
            $export_data[$k+1][] = $order_new_list[$v['order_id']]['order_sn'];
            $pay_totals += $export_data[$k+1][] = floatval($v['pay_price']);
            $commis_totals += $export_data[$k+1][] = floatval($v['invite_rates'] + $v['invite_rates_two']+$v['invite_rates_three']);
            $export_data[$k+1][] = $order_new_list[$v['order_id']]['store_name'];
            $export_data[$k+1][] = $order_new_list[$v['order_id']]['store_id'];
            $export_data[$k+1][] = $order_new_list[$v['order_id']]['buyer_name'];
            $export_data[$k+1][] = $order_new_list[$v['order_id']]['buyer_id'];
            $export_data[$k+1][] = $order_new_list[$v['order_id']]['goods_name'];
            $k++;
        }
        $count = count($export_data);
        $export_data[$count][] = '合计';
        $export_data[$count][] =  '';
        $export_data[$count][] = '';
        $export_data[$count][] = $pay_totals;
        $export_data[$count][] = $commis_totals;
        $csv = new Csv();
        $export_data = $csv->charset($export_data,CHARSET,'gbk');
        $file_name = $_GET['query_type'] == 'timeout' ? 'timeout_code' : 'xiaofei_code';
        $csv->filename = $ob_id.'-'.$file_name;
        $csv->export($export_data);
    }



    public function get_bill_xmlOp()
    {
        $model_bill = Model('fenxiao_bill');
        $condition = array();
        list($condition, $order) = $this->_get_bill_condition($condition);
//        dd($condition);
        $bill_list = $model_bill->getAgBillList($condition, '*', $_POST['rp'], $order);
        $data = array();
        $data['now_page'] = $model_bill->shownowpage();
        $data['total_num'] = $model_bill->gettotalnum();
        foreach ($bill_list as $bill_info) {
            $list = array();
            if ($bill_info['ob_state']) {
                $list['operation'] = "<a class=\"btn green\" href=\"index.php?act=agent_bill&op=show_bill&ob_id={$bill_info['ob_id']}\"><i class=\"fa fa-list-alt\"></i>查看</a>";
            } else {
                $list['operation'] = "<a class=\"btn orange\" href=\"index.php?act=agent_bill&op=deal_bill&ob_id={$bill_info['ob_id']}\"><i class=\"fa fa-gavel\"></i>处理</a>";
            }
            $list['ob_id'] = $bill_info['ob_id'];
            $list['ob_order_totals'] = ncPriceFormat($bill_info['ob_order_totals']);
            $list['ob_shop_orders_tatals'] = ncPriceFormat($bill_info['ob_shop_orders_tatals']);
            $list['ob_result_totals'] = ncPriceFormat($bill_info['ob_result_totals']);
            $list['ob_create_date'] = date('Y-m-d', $bill_info['ob_create_date']);
            $list['ob_store_name'] = $bill_info['ob_agent_name'];
            $list['ob_start_date'] = date('Y-m-d', $bill_info['ob_start_date']);
            $list['ob_end_date'] = date('Y-m-d', $bill_info['ob_end_date']);
//            $list['ob_commis_totals'] = ncPriceFormat($bill_info['ob_commis_totals']);
            $list['ob_store_id'] = $bill_info['ob_agent_id'];
            $data['list'][$bill_info['ob_id']] = $list;
        }
        exit(Tpl::flexigridXML($data));
    }

    public function deal_billOp()
    {
        $ob_id = $_GET['ob_id'];
        if (!$ob_id) {
            showMessage('参数错误', '', 'html', 'error');
        }
        $model_bill = Model('fenxiao_bill');
        $bill = $model_bill->getAgOrderBillInfo(['ob_id' => $ob_id]);
        if (!$bill['ob_state']) {
            DB::beginTransaction();
            try {
                $model_member = Model('member');
                $model_pd = Model('predeposit');
                $member_info = $model_member->getMemberInfoByID($bill['ob_agent_id']);
                $data['total_predeposit'] = $member_info['total_predeposit'] + $bill['ob_result_totals'];
                $data['available_predeposit'] = $member_info['available_predeposit'] + $bill['ob_result_totals'];
                $result = $model_member->editMember(['member_id' =>$bill['ob_agent_id']], $data);
                if (!$result) {
                    throw new Exception('处理结算信息失败');
                }
                $model_bill->editAgBill(['ob_id'=>$ob_id],['ob_state' => 1]);
                $admininfo = $this->getAdminInfo();

                $data_pd['member_id'] = $member_info['member_id'];
                $data_pd['member_name'] = $member_info['member_name'];
                $data_pd['amount'] = $bill['ob_result_totals'];
                $data_pd['admin_name'] = $admininfo['name'];
                $data_pd['month'] = $bill['os_month'];
                $model_pd->changePd('ag_jiesuan', $data_pd);
                DB::commit();
                showMessage('处理成功!');
            } catch (Exception $e) {
                DB::rollback();
            }
        }
        showMessage('该账单已结算', '', 'html', 'error');
    }

    /**
     * 合并相同代码
     */
    private function _get_bill_condition($condition) {
        if ($_GET['query_year'] && $_GET['query_month']) {
            $_GET['os_month'] = intval($_GET['query_year'].$_GET['query_month']);
        } elseif ($_GET['query_year']) {
            $condition['os_month'] = array('between',$_GET['query_year'].'01,'.$_GET['query_year'].'12');
        }
        if (!empty($_GET['os_month'])) {
            $condition['os_month'] = intval($_GET['os_month']);
        }
        if ($_REQUEST['query'] != '' && in_array($_REQUEST['qtype'],array('ob_no','ob_store_name'))) {
            $condition[$_REQUEST['qtype']] = $_REQUEST['query'];
        }
        if (is_numeric($_GET["ob_state"])) {
            $condition['ob_state'] = intval($_GET["ob_state"]);
        }
        if (is_numeric($_GET["ob_no"])) {
            $condition['ob_no'] = intval($_GET["ob_no"]);
        }
        if (is_numeric($_GET["ob_id"])) {
            $condition['ob_id'] = intval($_GET["ob_id"]);
        }
        if ($_GET['ob_store_name'] != ''){
            if ($_GET['jq_query']) {
                $condition['ob_store_name'] = $_GET['ob_store_name'];
            } else {
                $condition['ob_store_name'] = array('like',"%{$_GET['ob_store_name']}%");
            }
        }
        $sort_fields = array('ob_id','ob_start_date','ob_end_date','ob_order_totals','ob_shipping_totals','ob_commis_totals','ob_order_return_totals','ob_commis_return_totals','ob_store_cost_totals','ob_result_totals','ob_create_date','ob_state','ob_store_id');
        if (in_array($_REQUEST['sortorder'],array('asc','desc')) && in_array($_REQUEST['sortname'],$sort_fields)) {
            $order = $_REQUEST['sortname'].' '.$_REQUEST['sortorder'];
        } else {
            $order = 'ob_id desc';
        }
        return array($condition,$order);
    }

    public function jiesuanOp()
    {
        $year = $_GET['year'];
        $month = $_GET['month'];
        if ($year > date('Y')) {
            output_error('参数错误');
        }
        if ($month > date('n')) {
            output_error('参数错误');
        }
        $fisrtDay = $year . $month . '01';
        $os_start_date = strtotime($fisrtDay);
        $os_end_date = strtotime("$fisrtDay +1 month") - 1;
        $ag_bill = [];
        // 查出所有代理
        $agent = Model("agent");
        $store = Model('store');
        $member = Model('member');
        $order = Model('order');
        $vr_orders = Model('vr_order');

        $agent_list = $agent->getAgentList();
        foreach($agent_list as $key => $value){
            //根据代理区域查商圈店铺
            if($value['type']==0) {
                $where['province_id'] = $value['province_id'];
                $member_condition['member_provinceid'] = $value['province_id'];
            }
            if($value['type']==1) {
                $where['city_id'] = $value['city_id'];
                $member_condition['member_cityid'] = $value['city_id'];
            }
            if($value['type']==2) {
                $where['area_id'] = $value['area_id'];
                $member_condition['member_areainfo'] = $value['area_id'];
            }
            $where['store_class'] = 1;

            $member_list = $member->getMemberList($member_condition);
            $member_id = '';
            foreach($member_list as $va){
                $member_id .= $va['member_id'].",";
            }
            // 实物订单
            $order_condition['buyer_id'] = array('in',trim($member_id,','));
            $order_condition['order_state'] = 20;
            $order_condition['refund_state'] = 0;
            $order_condition['payment_time'] = ['between', $os_start_date . ',' . $os_end_date];
            $true_order = 0; // 真实订单总额
            $vr_order = 0;  // 虚拟订单总额
            $true_order_total = 0;  // 除去佣金运费实物订单总额
            $vr_order_total = 0;  // 除去佣金虚拟订单总额
            $true_orderlist = $order->getOrderList($order_condition);
            $true_ex_money = 0;  // 实物订单佣金运费总额
            $vr_ex_money = 0;  // 虚拟订单佣金总额
            foreach($true_orderlist as $va1){
                $true_order += $va1['order_amount'];
                $true_ex_money += $va1['invite_rates']+$va1['invite_rates_two']+$va1['invite_rates_three']+$va1['store_rates']+$va1['shipping_fee'];
                $true_order_total+= $va1['order_amount']-$true_ex_money;
            }
            // 虚拟订单
            $vr_orderlist = $vr_orders->getOrderList($order_condition);
            foreach($vr_orderlist as $va2){
                $vr_order += $va2['order_amount'];
                $vr_ex_money += $va2['invite_rates']+$va2['invite_rates_two']+$va2['invite_rates_three']+$va2['store_rates'];
                $vr_order_total+= $va2['order_amount']-$vr_ex_money;
            }
            $order_total = $true_order_total+$vr_order_total;
            $sq_bill_money = 0;
            $store_list = $store->getStoreList($where);
            // 从商圈结算表获取结算金额
            foreach($store_list as $k => $v){
                $wheresq['os_month'] = $year.$month;
                $wheresq['ob_store_id'] = $v['store_id'];
                $res = $sq_bill = Model('sq_bill')->where($wheresq)->find();
//                if(empty($res)){
//                    showMessage('请先结算商圈余额', '', 'html', 'error');
//                    die;
//                }
                $sq_bill_money = $sq_bill_money+$res['ob_result_totals'];
            }
            $ag_bill[$key]['aid'] = $value['member_id'];
            $ag_bill[$key]['order_amount'] = $true_order+$vr_order;
            $ag_bill[$key]['ex_money'] = $vr_ex_money+$true_ex_money;
            $ag_bill[$key]['sq_bill_money'] = $sq_bill_money;
            $ag_bill[$key]['member_order_totals'] = $order_total;
            $ag_bill[$key]['total'] = $order_total + $sq_bill_money;
        }

//        $fenxiao_bill_model = Model('fenxiao_bill');
//        $res = $fenxiao_bill_model->checkSqBill($os_start_date);
//        if ($res) {
//            exit(Tpl::flexigridXML($res));
//            output_error('该日期已结算');
//        }
        $data_bill = [];
        foreach ($ag_bill as $k => $v) {
            $member_name = $member->getMemberInfoByID($v['aid'],'member_name');
            $data_bill[$k]['ob_no'] = $year . $month . $v['aid'];
            $data_bill[$k]['ob_start_date'] = $os_start_date;
            $data_bill[$k]['ob_end_date'] = $os_end_date;
            $data_bill[$k]['os_month'] = $year . $month;
            $data_bill[$k]['ob_state'] = 0;
            $data_bill[$k]['ob_agent_id'] = $v['aid'];
            $data_bill[$k]['ob_agent_name'] = $member_name['member_name'];
            $data_bill[$k]['ob_shop_orders_tatals'] = $v['sq_bill_money']; // 商圈结算总额
            $data_bill[$k]['ob_member_order_totals'] = $v['member_order_totals']; // 用户订单总额
            $data_bill[$k]['ob_order_totals'] = $v['order_amount']; // 订单总额
            $data_bill[$k]['ob_commis_totals'] = $v['ex_money']; // 佣金总额
            $data_bill[$k]['ob_result_totals'] = $v['total']; // 结算总额
            $data_bill[$k]['ob_create_date'] = time();
        }
        $res = Model()->table('ag_bill')->insertAll($data_bill);
        exit(Tpl::flexigridXML($data_bill));
    }

}
